package com.xbongbong.paas.service.field;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.sys.domain.entity.UserEntity;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author 吴峰
 * @date 2022/04/01 9:56
 */
@Service("userGroupAnalysisHandlerImpl")
public class UserGroupAnalysisHandlerImpl extends AbstractFieldAnalysisHandler {


    @Override
    public List<Integer> fieldType() {
        return Arrays.asList(FieldTypeEnum.USER_GROUP.getType());
    }


    @Override
    public Object getValue(FieldAttrEntity fieldAttrEntity, PaasFormDataEntity paasFormDataEntity, JSONObject data, FieldAnalysisPoJo fieldAnalysisPoJo) throws XbbException {
        List<String> list = JSON.parseArray(JSON.toJSONString(data.get(fieldAttrEntity.getAttr())), String.class);
        if (CollectionUtils.isNotEmpty(list)) {
            List<ReturnUserAndDepartmentPojo> resultList = new ArrayList<>();
            Map<String, UserEntity> userEntityMap = fieldAnalysisPoJo.getUserMap();
            list.forEach(item->{
                ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                if (!userEntityMap.containsKey(item)) {
                    return;
                }
                returnUserAndDepartmentPojo.setId(item);
                returnUserAndDepartmentPojo.setName(userEntityMap.get(item).getName());
                resultList.add(returnUserAndDepartmentPojo);
            });
        }
        return data.get(fieldAttrEntity.getAttr());
    }
}
